<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>商品编辑</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-row>

                <el-col :span="8">
                    <div class="content-title">商品名称</div>
                    <el-input type="text" placeholder="请输入内容" v-model="product.pName" style="width:80%" maxlength="20"
                        show-word-limit>
                    </el-input>
                </el-col>
                <el-col :span="8">
                    <div class="content-title">商品图片</div>
                    <el-upload class="avatar-uploader" action="/uploadContent/uploading.do" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="product.pPic_1" :src="product.pPic_1" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <!--<div class="crop-demo">
                        <el-image style="width: 100px; height: 100px" :src="product.pPic_1"
                            :preview-src-list="[product.pPic_1]">
                        </el-image>

                        <div class="crop-demo-btn">选择图片
                            <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage" />
                        </div>
                    </div>-->
                </el-col>
                <el-col :span="6">
                    <div class="content-title">商品分类</div>
                    <el-select v-model="product.shelfId" multiple placeholder="请选择">
                        <el-option v-for="item in shelf" :key="item.id" :label="item.shelfName" :value="item.id">
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="2">
                    <el-row>
                        <el-button class="editor-btn" type="primary" @click="submit">提交</el-button>
                    </el-row>
                </el-col>
            </el-row>
            <el-row>
                <el-col v-show="product.pId" :span="16">
                    <div class="content-title">规格属性
                        <el-button style="float: right;margin-right: 20px;" @click="add" type="text">新增规格</el-button>
                    </div>

                    <el-row v-for="(item, i) in specifications" :key="item.id" style="margin:5px">
                        <!--<el-col :span="4">
                            <div class="crop-demo">
                                <el-image style="width: 80px; height: 80px" :src="item.pictures"
                                    :preview-src-list="item.pictures">
                                </el-image>
                                
                            </div>
                        </el-col>-->
                        <el-col style="padding-top: 10px;" :span="4">
                            <el-input v-model="item.specificationName" placeholder="请输入规格名"></el-input>
                        </el-col>
                        <el-col :span="6">
                            <el-row style="margin:10px">
                                <el-col :span="8">
                                    <div class="content-type">原价</div>
                                </el-col>
                                <el-col :span="16">
                                    <el-input-number v-model="item.originSpecificationPrice" @change="handleChange" :min="0"
                                        :max="9999" label="规格原价"></el-input-number>
                                </el-col>
                            </el-row>
                        </el-col>
                        <el-col :span="6">
                            <el-row style="margin:10px">
                                <el-col :span="8">
                                    <div class="content-type">价格</div>
                                </el-col>
                                <el-col :span="16">
                                    <el-input-number v-model="item.specificationPrice" @change="handleChange" :min="0"
                                        :max="9999" label="规格价格"></el-input-number>
                                </el-col>
                            </el-row>
                        </el-col>
                        <el-col :span="7">
                            <el-row style="margin:10px">
                                <el-col :span="10">
                                    <div class="content-type">规格库存</div>
                                </el-col>
                                <el-col :span="14">
                                    <el-input-number v-model="item.stock" @change="handleChange" :min="0" :max="9999"
                                        label="描述文字"></el-input-number>
                                </el-col>
                            </el-row>
                        </el-col>
                        <el-col :span="1">
                            <el-button type="text" style="margin:10px" icon="el-icon-delete"
                                @click="dodelete(i)"></el-button>
                        </el-col>
                    </el-row>
                </el-col>
                <el-col v-show="!product.pId" :span="16">
                    <div class="content-title">商品属性</div>
                    <el-row style="margin:20px">
                        <el-col :span="12">
                            <div class="content-type">商品价格</div>
                        </el-col>
                        <el-col :span="12">
                            <el-input-number v-model="product.pNowPrice" @change="handleChange" :min="0" :max="9999"
                                label="描述文字"></el-input-number>
                        </el-col>
                    </el-row>
                    <el-row style="margin:20px">
                        <el-col :span="12">
                            <div class="content-type">商品库存</div>

                        </el-col>
                        <el-col :span="12">
                            <el-input-number v-model="product.pStock" @change="handleChange" :min="0" :max="9999"
                                label="描述文字"></el-input-number>
                        </el-col>
                    </el-row>
                </el-col>
                <!--<el-col :span="8">
                    <div class="content-title">售卖限制</div>
                    <el-row style="margin:20px">
                        <el-col :span="12">
                            <div class="content-type">最大售卖数量</div>

                        </el-col>
                        <el-col :span="12">
                            <el-input-number v-model="product.maxbuy" @change="handleChange" :min="0" :max="999"
                                label="描述文字"></el-input-number>
                        </el-col>
                    </el-row>
                    <el-row style="margin:20px">
                        <el-col :span="12">
                            <div class="content-type">最小售卖数量</div>
                        </el-col>
                        <el-col :span="12">
                            <el-input-number v-model="product.minbuy" @change="handleChange" :min="0" :max="999"
                                label="描述文字"></el-input-number>
                        </el-col>
                    </el-row>
                    <el-row v-if="product.pSupplierId == 2144" style="margin:20px">
                        <el-col :span="12">
                            <div class="content-type">标签</div>
                        </el-col>
                        <el-col :span="12">
                            <template>
                                <el-select v-model="product.label" placeholder="请选择">
                                    <el-option v-for="item in cb" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </template>
                        </el-col>
                    </el-row>
                </el-col>-->
                <el-col :span="8">
                    <div class="content-title">文章内容</div>
                    <quill-editor ref="myTextEditor" v-model="product.pInfo" :options="editorOption"></quill-editor>
                </el-col>
            </el-row>

            <!--<el-dialog title="裁剪图片" :visible.sync="dialogVisible" width="30%">
                <vue-cropper aspectRatio=1 ref='cropper' :src="imgSrc" :ready="cropImage" :zoom="cropImage"
                    :cropmove="cropImage" style="width:100%;height:300px;"></vue-cropper>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="cancelCrop">取 消</el-button>
                    <el-button type="primary" @click="imageuploaded(); dialogVisible = false">确 定</el-button>
                </span>
            </el-dialog>-->
        </div>
    </div>
</template>

<script>
import VueCropper from 'vue-cropperjs';
import { addPicture, saveOrUpdateProduct, getShopShelf, getProductById, getSpecifications, updateSpecifications } from '../../api/prodect';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { quillEditor } from 'vue-quill-editor';
var toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // toggled buttons
    [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
    ['image'] // 链接、图片、视频-----['link', 'image', 'video']
];
var handlers = {
    image: function image() {
        var self = this;
        var fileInput = this.container.querySelector('input.ql-image[type=file]');
        if (fileInput === null) {
            fileInput = document.createElement('input');
            fileInput.setAttribute('type', 'file');
            // 可设置上传图片的格式
            fileInput.classList.add('ql-image');
            // 监听选择文件
            fileInput.addEventListener('change', function () {
                let reader = new FileReader();
                reader.readAsDataURL(fileInput.files[0]);
                reader.onload = e => {
                    let baseData = e.target.result;
                    var _this = this;
                    var quality = 0.8; //压缩图片的质量
                    var oldimglength = baseData.length; //压缩前的大小
                    var compresRadio = 0; // 压缩率

                    var canvas = document.createElement('canvas'); //创建画布
                    var ctx = canvas.getContext('2d');

                    var img = new Image();
                    img.src = baseData;
                    img.onload = function () {
                        var width = img.width;
                        var height = img.height;
                        canvas.width = 800; //这里可以自定义你的图片大小
                        canvas.height = 800 * (img.height / img.width);
                        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                        var cdata = canvas.toDataURL('image/jpeg', quality); //将图片转为Base64 之后预览要用
                        let plist = [];
                        plist.push(cdata.split(',')[1]);
                        addPicture(plist).then(res => {
                            console.log(res.data[0]);
                            length = self.quill.getSelection(true).index;
                            self.quill.insertEmbed(length, 'image', res.data[0]);
                            self.quill.setSelection(length + 1);
                            fileInput.value = '';
                        });
                    };
                };
            });
            this.container.appendChild(fileInput);
        }
        fileInput.click();
    }
};
export default {
    name: 'upload',
    data: function () {
        return {
            num: 0,
            defaultSrc: require('../../assets/img/img.jpg'),
            fileList: [],
            shelf: [],
            imgSrc: '',
            cropImg: '',
            dialogVisible: false,
            dialogImageUrl: '',
            disabled: false,
            product: {
                pName: '',
                pNowPrice: 0.1,
                pIfSale: 0,
                pStock: 9999,
                pPic_1: '',
                pInfo: '',
                minbuy: 0,
                maxbuy: 999,
                shelfId: [],

                pIfShowOriginalPrice: 1,
                pOriginalPrice: 0,
                pDeleteFlag: 0,
                pPostageMode: 0,
                distributionMode: 0
            },
            specifications: [],
            options: [],
            content: '',
            editorOption: {
                modules: {
                    toolbar: {
                        container: toolbarOptions, // 工具栏选项
                        handlers: handlers // 事件重写
                    }
                }
            }
        };
    },
    components: {
        VueCropper,
        quillEditor
    },
    methods: {
        handleAvatarSuccess(res, file) {
            console.log(res);
            this.product.pPic_1 = res.data
            //this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            //const isJPG = file.type === 'image/jpeg';
            const isLt5M = file.size / 1024 / 1024 < 5;
            if (!isLt5M) {
                this.$message.error('上传图片大小不能超过 5MB!');
            }
            return isLt5M;
        },
        onEditorChange({ editor, html, text }) {
            this.content = html;
        },
        setImage(e) {
            const file = e.target.files[0];
            if (!file.type.includes('image/')) {
                return;
            }
            const reader = new FileReader();
            reader.onload = event => {
                this.dialogVisible = true;

                this.imgSrc = event.target.result;
                this.$refs.cropper && this.$refs.cropper.replace(event.target.result);
            };
            reader.readAsDataURL(file);
        },
        //压缩图片
        compressImage: function (bdata) {
            var _this = this;
            var quality = 0.5; //压缩图片的质量
            var oldimglength = bdata.length; //压缩前的大小
            var compresRadio = 0; // 压缩率

            var canvas = document.createElement('canvas'); //创建画布
            var ctx = canvas.getContext('2d');

            var img = new Image();
            img.src = bdata;
            img.onload = function () {
                var width = img.width;
                var height = img.height;
                canvas.width = 500; //这里可以自定义你的图片大小
                canvas.height = 500 * (img.height / img.width);
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                var cdata = canvas.toDataURL('image/jpeg', quality); //将图片转为Base64 之后预览要用
                let plist = [];
                plist.push(cdata.split(',')[1]);
                addPicture(plist).then(res => {
                    _this.defaultSrc = res.data[0];
                    _this.product.pPic_1 = res.data[0];
                });
            };
        },
        cropImage() {
            this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
        },
        cancelCrop() {
            this.dialogVisible = false;
            this.cropImg = this.defaultSrc;
        },
        imageuploaded() {
            this.compressImage(this.cropImg);
        },
        add() {
            this.specifications.unshift({
                "productId": this.product.pId,
                "specificationName": "默认规格",
                "specificationMsg": "默认规格",
                "specificationPrice": 0,
                "characteristic": "",
                "pictures": this.product.Pic_1,
                "stock": 0
            })
        },
        dodelete(i) {
            this.specifications.splice(i, 1);
        },
        submit() {
            if (this.product.shelfId.length == 0) {
                this.$message({
                    message: '必须要有至少一个分类',
                    type: 'error'
                });
                return
            }
            this.product.pIfShowOriginalPrice = 1
            saveOrUpdateProduct(this.product).then(res => {
                this.product.pId = res.data;
                if (this.specifications.length > 0) {
                    updateSpecifications(this.product.pId, this.specifications).then(
                        e => {
                            this.$message({
                                message: '商品操作成功',
                                type: 'success'
                            });
                        }
                    )
                } else {
                    getSpecifications(this.product.pId).then(e => {
                        this.specifications = e.data
                        this.$message({
                            message: '商品操作成功',
                            type: 'success'
                        });
                    })
                }
            });
        },
        handleChange() { },
        //从URL中获取指定参数
        getQuery: function (name) {
            const reg = new RegExp(name + '=([^&]*)(&|$)', 'i');
            const r = window.location.hash.match(reg);
            if (r != null) return unescape(r[1]);
            return '';
        },
        getUrlParam(name) {
            return (
                decodeURIComponent(
                    (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')
                ) || null
            );
        },
        initialization() {
            this.cropImg = this.defaultSrc;
            let s = this.getUrlParam('id');
            if (s != 0) {
                getProductById(s).then(res => {
                    this.product = res.data;
                });
                getSpecifications(s).then(e => {
                    this.specifications = e.data
                })
            } else {
                this.product = {
                    pName: '',
                    pNowPrice: 0.1,
                    pIfSale: 0,
                    pStock: 9999,
                    pPic_1: '',
                    pInfo: '',
                    minbuy: 0,
                    maxbuy: 999,
                    shelfId: [],
                    pIfShowOriginalPrice: 1,
                    pOriginalPrice: 0,
                    pDeleteFlag: 0,
                    pPostageMode: 0,
                    distributionMode: 0
                };
            }
            getShopShelf().then(res => {
                this.shelf = res.data;
            });
        }
    },
    activated() {
        this.initialization();
    },
    created() {
        this.initialization();
    }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.content-title {
    font-weight: 400;
    line-height: 50px;
    margin: 10px 0;
    font-size: 22px;
    color: #1f2f3d;
}

.content-type {
    font-size: 18px;
    color: #8f8f8f;
}

.pre-img {
    width: 100px;
    height: 100px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 5px;
}

.crop-demo {
    display: flex;
    align-items: flex-end;
}

.crop-demo-btn {
    position: relative;
    width: 100px;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    margin-left: 30px;
    background-color: #409eff;
    color: #fff;
    font-size: 14px;
    border-radius: 4px;
    box-sizing: border-box;
}

.crop-input {
    position: absolute;
    width: 100px;
    height: 40px;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
}

.ql-container {
    min-height: 200px;
}
</style>